package com.shakespace.artofandroid.chapter07anim

import android.graphics.Camera
import android.view.animation.Animation
import android.view.animation.Transformation

/**
 * created by  shakespace
 * 2020/5/1  22:34
 */
/**
 * 通常很少自定义 view 动画
 * 如果需要，一般只需要重写
 * initialize ： 做一些初始化操作
 * applyTransformation： 做对应的矩阵变换
 *
 * 以下是 围绕Y轴旋转，同时沿着x轴平移的效果
 */
class Rotate3DAnimation(
    var fromDegree: Float, val toDegree: Float,
    val centerX: Float, val centerY: Float,
    val depthZ: Float, val reverse: Boolean
) : Animation() {
    var camera: Camera? = null

    override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
//        super.applyTransformation(interpolatedTime, t)
        val fromDegree = fromDegree
        var degrees = fromDegree + ((toDegree - fromDegree)) * interpolatedTime
        val centerX = centerX
        val centerY = centerY
        val camera = camera
        val matrix = t?.matrix
        camera?.apply {
            save()
            if (reverse) {
                translate(0.0f, 0.0f, depthZ * interpolatedTime)
            } else {
                translate(0.0f, 0.0f, depthZ * (1.0f - interpolatedTime))
            }
            rotateY(degrees)
            getMatrix(matrix)
            restore()
            matrix?.preTranslate(-centerX, -centerY)
            matrix?.postTranslate(centerX, centerY)
        }
    }

    override fun initialize(width: Int, height: Int, parentWidth: Int, parentHeight: Int) {
        super.initialize(width, height, parentWidth, parentHeight)
        camera = Camera()
    }
}